import { onMounted } from 'vue';
import Signature from './common';
import { download } from "./common/tools";
import type { ImgMime, SignActions, SignatureOptions, SignOptions } from "./typing";

const IExt: Record<string, ImgMime> = {
  png: 'image/png',
  jpg: 'image/jpeg',
  jpeg: 'image/jpeg',
  svg: 'image/svg+xml'
}

const noop = () => { };

const noopSignature = {
  undo: noop, clear: noop, isEmpty: noop, toDataURL: noop
} as Signature;

/**
 * 电子签名的 hooks
 * @param canvas 一个获取canvas元素的回调函数
 * @param options 可选项
 * @returns 电子签名可选的操作
 */
const useESign = (
  canvasDom: () => HTMLCanvasElement | undefined,
  options: SignOptions = {}
): SignActions => {
  let esign = noopSignature;
  const { type = 'png', quality = 0.8 } = options;
  let ext = type;
  const getESignatureOptions = () => {
    delete options.type;
    delete options.quality;
    return options as SignatureOptions;
  }

  onMounted(() => {
    if (typeof canvasDom === 'function') {
      const canvas = canvasDom();
      if (canvas) {
        esign = new Signature(canvas, getESignatureOptions());
        return console.debug('[e-signature] initialization succeeded.');
      }
    }
    console.debug('[e-signature] initialization failed.');
  });

  /**
   * 撤销功能
   */
  const undo = () => esign.undo();
  /**
   * 重置画布功能
   */
  const clear = () => esign.clear();
  /**
   * 变更画笔颜色
   */
  const changePenColor = () => {
    const color = `#${Math.random().toString(16).slice(2, 8)}`;
    esign.penColor = color;
  }

  /**
   * 获取电子签名的base64内容
   * @returns base64
   */
  const getData = () => {
    if (!esign.isEmpty()) {
      const _quality = Math.max(0, Math.min(1, quality));// [0,1]
      const mime = IExt[ext] || IExt[ext = 'png'];
      return esign.toDataURL(mime, _quality);
    }
  }

  /**
   * 保存为图片文件
   */
  const save = () => {
    const data = getData();
    if (data) {
      const filename = `esign-${Date.now().toString(32)}.${ext}`;
      download(data, filename);
    }
  }

  return {
    undo, clear, changePenColor, getData, save
  }
};

export {
  useESign as default,
  useESign
}